import csv
import sys
from ddt import ddt, data, unpack, file_data
from selenium import webdriver
import os
import time
import unittest

# 对测试文件进行读取
def uploadText(file_name):
    rows = []
    path = sys.path[0]
    with open(path + '/data/' + file_name, 'r', encoding='UTF-8') as f:
        readers = csv.reader(f, delimiter=',', quotechar='|')
        next(readers, None)
        for row in readers:
            temprows = []
            for i in row:
                temprows.append(i)
            rows.append(temprows)
        return rows


@ddt
class Upload(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.url = "http://127.0.0.1:8080/login.html"
        self.driver.maximize_window()
        url = self.url
        driver = self.driver
        driver.get(url)
        driver.find_element_by_id("username").clear()
        driver.find_element_by_id("password").clear()
        driver.find_element_by_id("username").send_keys("admin")
        driver.find_element_by_id("password").send_keys("123456")
        time.sleep(2)
        driver.find_element_by_id("submit").click()
        time.sleep(2)

    @data(*uploadText('Test_upload.txt'))
    @unpack
    def test_upload(self, path, singer):
        driver = self.driver
        time.sleep(2)
        driver.get("http://127.0.0.1:8080/list.html")
        # 点击添加歌曲按钮
        # time.sleep(10)
        driver.find_element_by_xpath("/html/body/div/div[2]/a[2]").click()
        driver.find_element_by_id("file").send_keys(os.path.abspath(path))
        driver.find_element_by_id("singer").send_keys(singer)
        time.sleep(2)
        driver.find_element_by_xpath("//*[@id='submit']").click()
        time.sleep(2)
        self.assertEqual("在线音乐", driver.title, msg="上传文件失败")

    def tearDown(self):
        self.driver.quit()
        time.sleep(2)

if __name__ == '__main__':
    unittest.main()